package com.xqls.util;


import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;

import java.util.Properties;

@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class UpdateInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //当前环境 MappedStatement，BoundSql，及sql取得
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        BoundSql newBoundSql = PageInterceptor.copyFromBoundSql(mappedStatement, boundSql, "/*!mycat:schema ="+ContextUtil.getTentNo()+" */"+boundSql.getSql());
        MappedStatement newMs = PageInterceptor.copyFromMappedStatement(mappedStatement, new  BoundSqlSqlSource(newBoundSql));
        mappedStatement=null;
        boundSql=null;
        invocation.getArgs()[0] = newMs;
        return invocation.proceed();
    }

    public Object plugin(Object arg0) {
        return Plugin.wrap(arg0, this);
    }

    public void setProperties(Properties arg0) {
    }

}
